1. /* sffffadd.cpp by K.Tsuru */
  2. // function ID = 710 DRADIX
  3. /******************************************************************
  4. SFraction class
  5. It provides the addition "m+n".
  6. (x.num/x.den)+(y.num/y.den)
  7. = (x.num*y.den+y.num*x.den)/(x.den*y.den) (1)
  8. = (x.num*(y.den/d1)+y.num*(x.den/d1)/((x.den/d1)*y.den) (2)
  9. The method (2) is the Knuth's one.This method is faster than
  10. the method (1).The method (3) the reduction is leaved until
  11. the number of figures exceed a threshold
  12. For example in the calculation using Pentium 120MHz
  13. 1/0! + 1/1! + 1/2! + .... 1/100!
  14. (1) 9.0 sec, (2) 7.1 sec, (3) less than 2.0 sec.
  15. However by updating hardware and compiler the method (2) becomes fastest.
  16. Then I adopt Knuth's method(2).
  17. ref: The Art of Computer Programing VOLUME 2 pp.330-331
  18. *******************************************************************/
  19. #ifndef SN_H
  20. #include "sn.h"
  21. #endif
  22. SFraction FFAdd(const SFraction& x, const SFraction& y){
  23. SFraction z;
  24. #if REDUCE_SIZE==0 //use Knuth's method
  25. SLong d1, d2, t, xd1;
  26. d1 = gcdL(x.den, y.den); // gcd
  27. if(d1.IsOne()) { // d1 == 1
  28. z.den = x.den*y.den;
  29. z.num = x.num*y.den + y.num*x.den;
  30. } else {
  31. xd1 = x.den/d1;
  32. t = x.num*(y.den/d1) + y.num*xd1; // numerator
  33. d2 = gcdL(t, d1);
  34. if(d2.IsOne()){
  35. z.den = xd1*y.den;
  36. z.num = t;
  37. } else {
  38. z.den = xd1*(y.den/d2);
  39. z.num = t/d2;
  40. }
  41. }
  42. if( !z.num.Sign(710) ) z.den.SetShort(1); //zero
  43. #ifndef NDEBUG
  44. assert(z.den.Sign(710) > 0);
  45. #endif
  46. z.reduceDone = true;
  47. return z;
  48. #else //REDUCE_SIZE!=0
  49. if(x.ReduceStepByStep()) {//use Knuth's method
  50. SLong d1, d2, t, xd1;
  51. d1 = gcdL(x.den, y.den); // gcd
  52. if(d1.IsOne()) { // d1 == 1
  53. z.den = x.den*y.den;
  54. z.num = x.num*y.den + y.num*x.den;
  55. } else {
  56. xd1 = x.den/d1;
  57. t = x.num*(y.den/d1) + y.num*xd1; // numerator
  58. d2 = gcdL(t, d1);
  59. if(d2.IsOne()){
  60. z.den = xd1*y.den;
  61. z.num = t;
  62. } else {
  63. z.den = xd1*(y.den/d2);
  64. z.num = t/d2;
  65. }
  66. }
  67. if( !z.num.Sign(710) ) z.den.SetShort(1); //zero
  68. #ifndef NDEBUG
  69. assert(z.den.Sign(710) > 0);
  70. #endif
  71. z.reduceDone = true;
  72. return z;
  73. } else {
  74. z.den = x.den*y.den;
  75. z.num = x.num*y.den + y.num*x.den;
  76. z.reduce(false);
  77. return z;
  78. }
  79. #endif
  80. }

sffffadd.cpp : last modifiled at 2017/10/20 10:42:44(2,299 bytes)
created at 2015/12/22 16:07:29
The creation time of this html file is 2017/10/21 15:10:35 (Sat Oct 21 15:10:35 2017).